package com.xyf.sys.controller;

import cn.hutool.core.lang.Validator;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyf.sys.config.CustomException;
import com.xyf.sys.config.MiniprogramConfig;
import com.xyf.sys.domain.*;
import com.xyf.sys.service.*;
import com.xyf.sys.util.R;
import com.xyf.sys.util.WechatHttpUtil;
import com.xyf.sys.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * @Author R-H
 * @Date 2024/2/181137
 * @Description
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户相关")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IUserPrinterService userPrinterService;
    @Autowired
    private IUserLogisticService userLogisticService;
    @Autowired
    @Qualifier(value = "clientConfig")
    private MiniprogramConfig.MiniConfig clientConfig;
    @Autowired
    @Qualifier(value = "manageConfig")
    private MiniprogramConfig.MiniConfig manageConfig;
    @Autowired
    private ISysPriceSchemeService priceSchemeService;
    @Autowired
    private ILogisticService logisticService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IWechatService wechatService;
    @Autowired
    private IUserRoleService userRoleService;

    /**
     * 用户信息修改
     *
     * @param user
     * @return
     */
    @ApiOperation("用户编辑")
    @PostMapping("/edit")
    public Object edit(@RequestBody UserVo user, HttpServletRequest request) {
        String appid = request.getHeader("APPID");
        if (StringUtils.isBlank(user.getUserId())){
            user.setUserId(request.getHeader("openid"));
        }
        user.setClient(clientConfig.getAppid().equals(appid));

        if (StringUtils.isNotBlank(user.getCode())) {
            String secret = appid.equals(clientConfig.getAppid()) ? clientConfig.getSecret() : manageConfig.getSecret();
            String data = WechatHttpUtil.getOpenId(appid, user.getCode(), secret);
            log.info("login data{} ", data);
            com.alibaba.fastjson2.JSONObject jsonObject = com.alibaba.fastjson2.JSONObject.parseObject(data);
            String openid = jsonObject.getString("openid");
            String unionid = jsonObject.getString("unionid");
            User record = userService.getUser(openid);
            if (record == null) {
                userService.create(openid, unionid, appid);
            }
            user.setUserId(openid);
        }
        userService.update(user);
        UserVo userVo = userService.getInfo(user.getUserId(), request.getHeader("APPID").equals(clientConfig.getAppid()));
        if (StringUtils.isNotBlank(userVo.getUnionid())){
            User serviceUser = userService.getUser(userVo.getUnionid(), manageConfig.getAppid());
            if (serviceUser != null && serviceUser.getDeptId() != null){
                List<Role> roleList = userRoleService.getRoleList(userVo.getId(), userVo.getDeptId());
                if (roleList.stream().filter(role -> "REGIMENT".equalsIgnoreCase(role.getRoleKey()) || "GUIDE".equalsIgnoreCase(role.getRoleKey())).findAny().isPresent()) {
                    UserVo manager = userService.getInfo(serviceUser.getId(), false, true);
                    userVo.setManagerUser(manager);
                }
            }
        }
        return R.ok(userVo);
    }

    @ApiOperation("角色授权")
    @PostMapping("/author")
    public Object authorUser(@RequestBody AuthorParam authorParam, HttpServletRequest request) {
        if (StringUtils.isBlank(authorParam.getUserId())){
            authorParam.setUserId(request.getHeader("openid"));
        }
        return R.ok(userService.authorUser(authorParam.getUserId(), authorParam.getAuthorUserId(), authorParam.getRoleId()));
    }

    /**
     * 查询附近的团长
     *
     * @param requestVo
     * @return
     */
    @ApiOperation("查询附件的团长")
    @PostMapping("/nearbyRegimentList")
    public Object nearbyRegimentList(@RequestBody NearbyRegimentListRequestVo requestVo) {
        BigDecimal longitude = requestVo.getLongitude().setScale(6, RoundingMode.UNNECESSARY);
        BigDecimal latitude = requestVo.getLatitude().setScale(6, RoundingMode.UNNECESSARY);
        PageHelper.startPage(requestVo.getPageNum(), requestVo.getPageSize());
        List<Dept> deptList = deptService.findRegimentDeptList(longitude, latitude, requestVo.getKeyword());
//        List<User> userList = userService.findNearbyRegimentList(longitude, latitude);
        PageInfo pageInfo = new PageInfo(deptList);
        return R.ok(pageInfo);
    }

    /**
     * 查询所属代理的用户列表
     *
     * @param requestVo
     * @return
     */
    @ApiOperation("查询我的用户列表")
    @PostMapping("/myUserList")
    public Object myUserList(@RequestBody UserListRequestVo requestVo, HttpServletRequest request) {
        String appId = request.getHeader("APPID");
        PageHelper.startPage(requestVo.getPageNum(), requestVo.getPageSize());
        List<User> userList = userService.getUserList(requestVo.getUserId(), requestVo.getKeyword(), appId.equals(clientConfig.getAppid()) ,requestVo.getRoleId());
        return R.ok(new PageInfo(userList));
    }


    @ApiOperation("查询用户详情")
    @GetMapping("/info")
    public Object info(@RequestParam String userId) {
        UserVo user = userService.getInfo(userId);
        if (StringUtils.isNotBlank(user.getUnionid())){
            User serviceUser = userService.getUser(user.getUnionid(), manageConfig.getAppid());
            if (serviceUser != null && serviceUser.getDeptId() != null){
                List<Role> roleList = userRoleService.getRoleList(user.getId(), user.getDeptId());
                if (roleList.stream().filter(role -> "REGIMENT".equalsIgnoreCase(role.getRoleKey()) || "GUIDE".equalsIgnoreCase(role.getRoleKey())).findAny().isPresent()) {
                    UserVo manager = userService.getInfo(serviceUser.getId(), false, true);
                    user.setManagerUser(manager);
                }
            }
        }
        return R.ok(user);
    }

    @ApiOperation("用户实名")
    @PostMapping("/realNameAuth")
    public R realNameAuth(@RequestBody UserRealName userRealName) {
        return R.ok(userService.userRealName(userRealName));
    }

    @ApiOperation("用户实名")
    @PostMapping("/realName")
    public R realName(@RequestBody UserAddress senderAddress) {
        logisticService.realName(senderAddress.getDeliveryId(), senderAddress.getRealName(), senderAddress.getRealId(), senderAddress.getMobile(), senderAddress.getProvince() + senderAddress.getCity() + senderAddress.getArea() + senderAddress.getTown() + senderAddress.getAddress());
        return R.ok();
    }


    @ApiOperation("用户编辑-添加打印机")
    @PostMapping("/savePrinter")
    public Object save(@RequestBody UserPrinter printer) {
        return R.ok(userPrinterService.save(printer));
    }

    @ApiOperation("用户编辑-移除打印机")
    @GetMapping("/delPrinter")
    public Object delPrinter(@RequestParam Long printerId) {
        return R.ok(userPrinterService.remove(printerId));
    }

    @ApiOperation("用户编辑-添加物流")
    @PostMapping("/saveLogistics")
    public Object saveLogistics(@RequestBody UserLogistic logistic) {
        return R.ok(userLogisticService.save(logistic));
    }

    @ApiOperation("用户编辑-删除物流")
    @GetMapping("/delLogistics")
    public Object delLogistics(@RequestParam Long logisticsId) {
        return R.ok(userLogisticService.remove(logisticsId));
    }

    @ApiOperation("用户-云打印验证码")
    @PostMapping("/print/captcha")
    public Object printCaptcha(@RequestBody UserPrintCaptchaParam printCaptchaParam) {
        return R.ok(userPrinterService.printCaptcha(printCaptchaParam.getPrinterId(), printCaptchaParam.getUserId()));
    }

    @ApiOperation("用户-云打印机绑定")
    @PostMapping("/printer/bind")
    public Object printerBind(@RequestBody UserPrintCaptchaParam printCaptchaParam) {
        return R.ok(userPrinterService.printerBind(printCaptchaParam.getPrinterId(), printCaptchaParam.getCaptcha(), printCaptchaParam.getUserId(), printCaptchaParam.getDeptId()));
    }

    @ApiOperation("用户-云打印机解绑")
    @PostMapping("/printer/unbind")
    public Object printerUnBind(@RequestBody UserPrintCaptchaParam printCaptchaParam) {
        return R.ok(userPrinterService.printerUnBind(printCaptchaParam.getId(), printCaptchaParam.getUserId()));
    }

    @ApiOperation("用户-云打印")
    @PostMapping("/print")
    public Object print(@RequestBody UserPrintParam printParam) {
        return R.ok(userPrinterService.cloudPrint(printParam.getId(), printParam.getWaybillPrinterData(), printParam.getUserId()));
    }

    @ApiOperation("用户-云打印结果订阅")
    @PostMapping("/printCallback")
    public String printCallback(@RequestBody Map<String,Object> body) {
        boolean bool = userPrinterService.printCallback(body);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", true);
        jsonObject.put("message", "");
        return JSON.toJSONString(jsonObject);
    }

    @ApiOperation("用户-移除所属部门")
    @PostMapping("/dept")
    public Object editDept(@RequestBody Map<String, Object> body, HttpServletRequest request) {
        return R.ok(userService.updateUserDept(body.get("id").toString(), body.get("userDeptId") == null ? null : Long.parseLong(body.get("userDeptId").toString()),  request.getHeader("OPENID")));
    }

    @ApiOperation("用户-添加所属部门")
    @PostMapping("/addUserDept")
    public Object editDept(@RequestBody UserDept userDept, HttpServletRequest request) {
        userService.addUserDept(userDept,  request.getHeader("OPENID"));
        UserVo userVo = userService.getInfo(userDept.getUserId(), request.getHeader("APPID").equals(clientConfig.getAppid()));
        return R.ok(userVo);
    }

    @ApiOperation("用户-删除所属部门")
    @PostMapping("/delUserDept")
    public Object delUserDept(@RequestBody UserDept userDept, HttpServletRequest request) {
        userService.removeDept(userDept,  request.getHeader("OPENID"));
        UserVo userVo = userService.getInfo(userDept.getUserId(), request.getHeader("APPID").equals(clientConfig.getAppid()));
        return R.ok(userVo);
    }

    @ApiOperation("用户-视频号配置")
    @PostMapping("/channelConfig")
    public Object channelConfig(@RequestBody ChannelConfig config, HttpServletRequest request) {
        userService.updateChannelConfig(config,  request.getHeader("OPENID"));
        return R.ok();
    }


    @ApiOperation("获取已添加到橱窗的商品列表")
    @PostMapping("/productList")
    public R productList(HttpServletRequest request) throws UnsupportedEncodingException {
//        String token = wechatService.getAccessToken("wx1b971f2389e507d5", "8470875a9e7783a41957205490574640");
//        JSONObject orderInfo = wechatService.queryChannelsOrder("3727336034811651328", token);
//        log.info("channel order info {}", orderInfo);
//        String accessToken2 = wechatService.getAccessToken("wxa0e0de3c6c6bb17d", "03538d1fa323e99a1aa5356d73100d43");
        ChannelConfig config = userService.getChannelConfig(Long.valueOf(request.getHeader("DEPTID")));
        if (config == null){
            return R.ok(null);
        }
        String accessToken = wechatService.getAccessToken(config.getWindowId(), config.getWindowSecret());
        com.alibaba.fastjson2.JSONObject param = new com.alibaba.fastjson2.JSONObject(4);
        param.put("page_size", 10);
        param.put("page_index", 1);
        param.put("need_total_num", true);
        param.put("query_cps_product", true);
        byte[] bytes = WechatHttpUtil.doWechatPost("https://api.weixin.qq.com/channels/ec/window/product/list/get?access_token=" + accessToken, param);
        com.alibaba.fastjson2.JSONObject jsonObject = com.alibaba.fastjson2.JSONObject.parseObject(new String(bytes, "UTF-8"));
        log.info(jsonObject.toJSONString());
        if (jsonObject.getInteger(  "errcode") == 0){
            JSONArray products = jsonObject.getJSONArray("products");
            for (int i = 0; i < products.size(); i++) {
                com.alibaba.fastjson2.JSONObject item = products.getJSONObject(i);
                com.alibaba.fastjson2.JSONObject infoParam = new com.alibaba.fastjson2.JSONObject(4);
                infoParam.put("product_id", item.getString("product_id"));
                infoParam.put("need_cps_product", true);
                byte[] bytes2 = WechatHttpUtil.doWechatPost("https://api.weixin.qq.com/channels/ec/window/product/get?access_token=" + accessToken, infoParam);
                com.alibaba.fastjson2.JSONObject object = com.alibaba.fastjson2.JSONObject.parseObject(new String(bytes2, "UTF-8"));
                if (object.getInteger("errcode") == 0){
                    item.put("product", object.getJSONArray("cps_products"));
                }
            }
            return R.ok(products);
        }
        return R.ok(null);
    }

    @ApiOperation("用户-查询团主")
    @PostMapping("/groupLeader")
    public Object groupLeader(@RequestBody Map<String, String> body, HttpServletRequest request) {
        PageHelper.startPage(Integer.valueOf(body.get("pageNum")), Integer.valueOf(body.get("pageSize")));
        PageInfo pageInfo = new PageInfo(deptService.getRoleDept("GROUPLEADER"));
        return R.ok(pageInfo);
    }

    @ApiOperation("清除")
    @PostMapping("/clean")
    public Object clean(@RequestBody Map<String, String> body, HttpServletRequest request) {
        userService.clean(body.get("id"));
        return R.ok();
    }
}
